import React, { useState, useRef, forwardRef, useImperativeHandle } from "react";

type TextSegment = {
    text: string;
    meta?: any; // 额外信息（如颜色、ID、类型等）
};

const initialContent: TextSegment[] = [
    { text: "这是一段普通文本，" },
    { text: "但某个词语", meta: { color: "red", id: 1 } },
    { text: "需要特殊处理。" }
];

export const EditableText = forwardRef((_, ref) => {
    const [content, setContent] = useState<TextSegment[]>(initialContent);
    const editableRef = useRef<HTMLDivElement>(null);
    const savedRange = useRef<Range | null>(null); // 保存光标位置

    // 保存当前光标位置
    const saveSelection = () => {
        const selection = window.getSelection();
        if (selection && selection.rangeCount > 0) {
            savedRange.current = selection.getRangeAt(0);
        }
    };

    // 恢复光标位置
    const restoreSelection = () => {
        const selection = window.getSelection();
        if (savedRange.current && selection) {
            selection.removeAllRanges();
            selection.addRange(savedRange.current);
        }
    };

    // 插入特殊块
    const insertSpecialBlock = (text: string, meta: any) => {
        restoreSelection(); // 恢复光标位置
        const selection = window.getSelection();
        if (selection && editableRef.current) {
            const range = selection.getRangeAt(0);
            const span = document.createElement("span");
            span.textContent = text;
            span.style.color = meta.color || "blue"; // 设置颜色
            span.dataset.meta = JSON.stringify(meta); // 设置自定义属性
            range.insertNode(span); // 在光标处插入特殊文本
            range.setStartAfter(span); // 设置光标位置在插入的文本后面
            selection.removeAllRanges();
            selection.addRange(range); // 更新选区
        }
    };

    const focus = () => {
        if (editableRef.current) {
            editableRef.current.focus(); // 聚焦到编辑器
        }
    };
    // 暴露给父组件的方法
    useImperativeHandle(ref, () => ({
        getContent: () => content, // 获取当前内容
        setContent: (newContent: TextSegment[]) => setContent(newContent), // 设置内容
        focus, // 聚焦到编辑器
        clear: () => setContent([]), // 清空内容
        getSelection: () => {
            const selection = window.getSelection();
            if (selection && editableRef.current) {
                const range = selection.getRangeAt(0);
                return range.toString(); // 返回选中的文本
            }
            return null;
        },
        // 在光标处插入文本
        insertTextAtCursor: (text: string) => {
            const selection = window.getSelection();
            if (selection && editableRef.current) {
                const range = selection.getRangeAt(0);
                range.deleteContents(); // 删除选中的内容
                const textNode = document.createTextNode(text);
                range.insertNode(textNode); // 在光标处插入文本
                range.setStartAfter(textNode); // 设置光标位置在插入的文本后面
                selection.removeAllRanges();
                selection.addRange(range); // 更新选区
            }
        },
        // 在光标处插入特殊文本
        insertSpecialTextAtCursor: (text: string, meta: any) => {
            focus(); // 聚焦到编辑器
            insertSpecialBlock(text, meta); // 插入特殊文本
        },
    }));

    const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
        saveSelection(); // 保存光标位置
        const selection = window.getSelection();
        if (selection && editableRef.current) {
            const range = selection.getRangeAt(0);
            const parentElement = range.startContainer.parentElement;

            // 如果光标在 isSpecial 块中，阻止删除键
            if (parentElement?.dataset?.meta && (event.key === "Backspace" || event.key === "Delete")) {
                event.preventDefault();
                selection.removeAllRanges();
                const newRange = document.createRange();
                newRange.selectNodeContents(parentElement);
                selection.addRange(newRange);
            }
        }
    };

    const handleMouseUp = () => {
        saveSelection(); // 保存光标位置
        const selection = window.getSelection();
        if (selection && editableRef.current) {
            const range = selection.getRangeAt(0);
            const parentElement = range.startContainer.parentElement;

            // 如果光标在 isSpecial 块中，选中整个块
            if (parentElement?.dataset?.meta) {
                selection.removeAllRanges();
                const newRange = document.createRange();
                newRange.selectNodeContents(parentElement);
                selection.addRange(newRange);
            }
        }
    };

    const [cursorPosition, setCursorPosition] = useState<{ x: number; y: number } | null>({x: 0, y: 0}); // 光标位置
        // 监听用户输入
        const handleInput = (event: React.FormEvent<HTMLDivElement>) => {
            const text = event.currentTarget.textContent || "";
            const selection = window.getSelection();
            if (selection && selection.rangeCount > 0) {
                const range = selection.getRangeAt(0);
                const rect = range.getBoundingClientRect();
                setCursorPosition({ x: rect.left, y: rect.bottom });
            }
            
        };

    const renderAsHTML = (content: TextSegment[]): string => {
        return content
            .map((segment) => {
                if (segment.meta) {
                    // 特殊文本：添加样式和自定义属性（如 data-meta）
                    return `<span style="color: blue; padding-left: 0.5em; padding-right: 0.5em" data-meta="${JSON.stringify(segment.meta)}">${segment.text}</span>`;
                }
                // 普通文本：直接转义（防止 XSS）
                return escapeHtml(segment.text);
            })
            .join(''); // 合并为完整 HTML
    };

    const escapeHtml = (text: string): string => {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    };

    return (<div>
        <div
            ref={editableRef}
            contentEditable
            onKeyDown={handleKeyDown}
            onMouseUp={handleMouseUp}
            onInput={handleInput}
            dangerouslySetInnerHTML={{ __html: renderAsHTML(content) }}
            style={{
                minHeight: "100px",
                maxHeight: "200px",
                border: "1px solid #ccc",
                padding: "8px",
                borderRadius: "4px",
                overflowY: "auto",
                whiteSpace: "pre-wrap",
                wordWrap: "break-word",
                fontSize: "16px",
                lineHeight: "1.5",
                resize: "vertical",
                outline: "none",
            }}
        />
                    {(
                <ul
                    style={{
                        position: "absolute",
                        top: cursorPosition.y + window.scrollY,
                        left: cursorPosition.x + window.scrollX,
                        background: "#fff",
                        border: "1px solid #ccc",
                        borderRadius: "4px",
                        listStyle: "none",
                        padding: "0",
                        margin: "0",
                        zIndex: 1000,
                        width: "200px",
                    }}
                >
                    {['1','2'].map((suggestion) => (
                        <li
                            key={suggestion}

                            style={{
                                padding: "8px",
                                cursor: "pointer",
                                borderBottom: "1px solid #eee",
                            }}
                        >
                            {suggestion}
                        </li>
                    ))}
                </ul>
            )}
            </div>
    );
});